/**
 * Copyright (c) 2016-2020 https://github.com/zhaohuatai
 *
 * contact 824069438@qq.com
 *  
 */
package org.zfes.snowy.auth.shiro.filter;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.zfes.snowy.auth.AuthConsts;
import org.zfes.snowy.auth.shiro.suser.SessionUser;

public class MultiLoginLimitUtil {
	
	public static void validateSessionLimit(Subject subject,Integer maxSession)throws Exception {
		
//		  Session newSession = subject.getSession();
//		  String newLoginUserName= subject.getPrincipal().toString();
//		  String newLoginOrgin=(String)newSession.getAttribute(AuthConsts.SESSION.SESSION_LOGINORGIN_KEY);
//		  Serializable newSessionId= newSession.getId();
//		
//		 DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager();
//	     DefaultWebSessionManager sessionManager = (DefaultWebSessionManager)securityManager.getSessionManager();
//	     Collection<Session> activeSessions = sessionManager.getSessionDAO().getActiveSessions();
//	     
//		 if(activeSessions!=null&&!activeSessions.isEmpty()){
//			 
//			List<Session> sessionList=activeSessions.parallelStream().filter(session->filterSession( session, newLoginUserName,newLoginOrgin,newSessionId)).collect(Collectors.toList());
//			if(sessionList!=null&&sessionList.size()>maxSession){
//				int limit=maxSession-1;
//				for(int i=sessionList.size()-1;i>=limit;i--){
//					sessionManager.getSessionDAO().delete(sessionList.get(i));
//				}
//				
//			}
//		 }
	}
	
	
	   
//		private static Boolean filterSession(Session session,String newLoginUserName,String newLoginOrgin,Serializable newSessionId){
//			SessionUser sessionUser=((SessionUser)session.getAttribute(AuthConsts.SESSION.SESSION_USER_KEY));
//			if(sessionUser==null){
//				return false;
//			}
//			String otherLoginUserName=sessionUser.getUsername();
//			String otherLoginOrgin=(String) session.getAttribute(AuthConsts.SESSION.SESSION_LOGINORGIN_KEY);
//			Serializable otherSessionId=(String) session.getId();
//			if((newLoginOrgin.equals(otherLoginOrgin))//终端类型相同
//				&&(newLoginUserName.equals(otherLoginUserName))//登录账号相同
//				&&(!otherSessionId.equals(newSessionId))){//sessionId不同
//				return true;
//			}
//			
//			return false;
//		}
}
